package com.imcoke.abchat.web.mapper;

import com.imcoke.abchat.common.SQLProvider;
import com.imcoke.abchat.domain.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @Author ccoke
 * @Description
 * @Date: 20:37 2017-11-27
 */
@Mapper
public interface UserMapper {

    @Select("SELECT role.`name` " +
            "FROM " +
            "tb_role role," +
            "tb_user_role userrole " +
            "WHERE userrole.uid = #{id} AND userrole.rid = role.id")
    List<String> selectRolesByUserId(@Param("id") Long id);

    @Select("SELECT * FROM tb_user WHERE id = #{id}")
    User selectUserById(@Param("id") Long id);

    @Select("SELECT * FROM tb_user WHERE username = #{username}")
    @Results({
            @Result(column = "id",property = "id"),
            @Result(column = "id",property = "roles",many = @Many(select = "selectRolesByUserId"))
    })
    User selectUserByUserName(@Param("username") String username);

    @Select("SELECT * FROM tb_user WHERE email = #{email}")
    User selectUserByEmail(@Param("email") String email);

    @Insert("INSERT INTO tb_user VALUES(null,#{username},#{password},#{email},#{headimage},#{nickname},#{regtime},#{lasttime},#{modifytime})")
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Long.class)
    int insertUser(User user);

    @Insert("<script>" +
            "insert into tb_user_role values" +
            "<foreach collection = 'roles' item = 'item' index = 'index' separator = ','>" +
            "(${uid},(SELECT id FROM tb_role WHERE name = #{item})"+")" +
            "</foreach>" +
            "</script>")
    int insertRoles4User(@Param("roles") List<String> roles,@Param("uid") Long uid);

    @UpdateProvider(type = SQLProvider.class,method = "updateUser")
    int updateUser(User user);
}
